#include "xen/imgui/imgui_layer.hpp"

#include "platform/opengl/opengl_context.hpp"
#include "xen/application.hpp"

namespace Xen {

ImGuiLayer::ImGuiLayer(): Layer("ImGUI Layer") {
}

ImGuiLayer::~ImGuiLayer() {
}

void ImGuiLayer::OnAttach() {
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;

    ImGui::StyleColorsDark();

    auto window = Application::Get().GetWindow().GetNativeWindow();
    auto gl_context = static_cast<OpenGLContext*>(Application::Get().GetWindow().GetNativeGlContext())->GetNativeContext();
    ImGui_ImplSDL2_InitForOpenGL(static_cast<SDL_Window*>(window), gl_context);
    ImGui_ImplOpenGL3_Init("#version 330 core");
}

void ImGuiLayer::OnDetach() {
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplSDL2_Shutdown();
    ImGui::DestroyContext();
}

void ImGuiLayer::Begin() {
    ImGui_ImplOpenGL3_NewFrame();
    ImGui_ImplSDL2_NewFrame(static_cast<SDL_Window*>(Application::Get().GetWindow().GetNativeWindow()));
    ImGui::NewFrame();
}

void ImGuiLayer::End() {
    ImGuiIO& io = ImGui::GetIO();
    Application& app = Application::Get();
    io.DisplaySize.x = app.GetWindow().GetSize().w;
    io.DisplaySize.y = app.GetWindow().GetSize().h;

    ImGui::Render();
    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}

void ImGuiLayer::OnImGuiRender() {
}

}
